#!/usr/bin/perl -w 

# Written By JEEN < aiatejin@gmail.com >
# http://jeen.tistory.com

use strict;
use warnings;
use Me2day;
use Data::Dumper;
use constant KEY => "74589a73e765e8a2df0fa030c38c28ad";

my ($me2day, $id, $pass);

init();
post(@ARGV);

sub post {
    my @arg = @_;

    if ($#arg == -1) {
	print STDERR "Usage : m2w [body] [tag]\n";
	print STDERR "ex> m2w 하얀_고양이를 말하려면 '_'는 필수입니다. \@:white-cat 언더바\n";
	exit 8;
    }

    my $text = join(" ", @arg);

    my $res;
    my ($post,$tag);
    if ($text =~ /@\:/) {
	($post, $tag) = split /@\:/, $text; #/
	    $res = $me2day->create_post( body => $post, tags => $tag );
    } else {
	$post = $text;
	$res = $me2day->create_post( body => $post );
    }
    if ($res->status_line =~ /200/) {
	$res->content =~ /<permalink>(.*?)<\/permalink>/;
	my $permalink = $1;
	print STDERR "글을 저장했습니다.\n";
	print STDERR "permalink: $permalink\n";
	print STDERR "body     : $post\n";
	print STDERR "tags     : $tag\n" if $tag;
    } else {
	print STDERR "Error : ".$res->status_line."\n";
    }
}
sub _connect {
    my ($username, $userkey) = @_;

    $me2day = Me2day->new( username => $username, user_key => $userkey, app_key => KEY );
    my $test = $me2day->noop;
    
    if ($test->status_line =~ /200/) {
	return ($me2day->{username}, $me2day->{password})
    } else {
	return;
    }
}

sub init {
    open my $fh, "<", $ENV{HOME}."/.me2day_info" or return create_info();
    my ($username, $userkey) = split("\t", (join "", <$fh>));
    ($id, $pass) = _connect($username, $userkey);
    unless ($id && $pass) {
	print STDERR "인증에 실패했습니다. 다시금 인증정보를 입력해주세요.\n";
	print STDERR "-----------------------------------------------------\n";
	return create_info();
    }

}

sub create_info {
    print "Me2day ID 를 입력해주세요 : ";
    my $username = <STDIN>;
    chomp $username;
    print "\"사용자키\"를 입력해주세요 : ";
    my $userkey = <STDIN>;
    chomp $userkey;
    ($id, $pass) = _connect($username, $userkey);
    if ($id && $pass) {
	open my $fh, ">", $ENV{HOME}."/.me2day_info";
	print $fh $username."\t".$userkey;
    } else {
	print STDERR "인증에 실패했습니다. Me2day ID와 사용자키를 확인하신 후 다시 입력해주세요\n";
	print STDERR "-------------------------------------------------------------------------\n";
	create_info();
    }
}

